//
//  DBStatusesViewModel.swift
//  大波微博swift
//
//  Created by 大波 on 16/3/3.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit
import SDWebImage

class DBStatusesViewModel: NSObject {
    
    var statuses: DBStatuses?
    
    func loadStatuses(since_id: Int, max_id: Int, loadStatusesCallBack: (statuse: [DBStatuses]?, error: NSError?) -> ()) {
        
        DBNetworkTool.shareNetworkTool.loadStatuses(since_id, max_id: max_id) { (statuses, error) -> () in
            
            if error != nil {
                
                loadStatusesCallBack(statuse: nil, error: error)
                
                return
            }
            
            // 守卫  没有则数据和错误都传空
            guard let array = statuses?["statuses"] as? [[String : AnyObject]] else {
                
                loadStatusesCallBack(statuse: nil, error: nil)
                
                return
            }
            
            // 定义空数组保存微博数据模型
            var statusesArr = [DBStatuses]()
            
            for dic in array {
                
                let statuse = DBStatuses(dic: dic)
                
                statusesArr.append(statuse)
            }
            
            // 通知控制器前下载图片
            self.loadWebImage(statusesArr, loadStatusesCallBack: loadStatusesCallBack)
        }
    }
    
    
    /// 下载图片
    func loadWebImage(statuses: [DBStatuses], loadStatusesCallBack: (statuse: [DBStatuses]?, error: NSError?) -> ()) {
        
        // 创建组
        let group = dispatch_group_create()
        
        var length: Int = 0
        
        for statuse in statuses {
            
            // 要下载的图片数组
            var urls = [NSURL]()
            
            if let downloadURL = statuse.picDataURL {
                
                urls = downloadURL
            }
            
            if let downloadURL = statuse.retweeted_status?.picDataURL {
                
                urls = downloadURL
            }
            
            for url in urls {
                
                // 进入组
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    
                    // 离开组
                    dispatch_group_leave(group)
                    
                    if error != nil {
                        
                        print("下载图片出错:\(error)")
                        
                        return
                    }
                    
                    let data = UIImagePNGRepresentation(image)
                    
                    length = data!.length
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            
            loadStatusesCallBack(statuse: statuses, error: nil)
        })
    }
    
    /// 发布微博(无图片)
    class func sendStatuse(status: String, image: UIImage?, finish: (error: NSError?) -> ()) {
        
        guard let access_token = DBUserAccountViewModel.shareUserAccountViewModel.userAccount?.access_token else {
            
            let error = DBNetworkError.DBNetworkEmptyAccess_token.error()
            
            finish(error: error)
            
            return
        }
        
        var url = ""
        
        let parameters = [
            
            "access_token" : access_token,
            
            "status" : status
        ]
        
        if image == nil {
                        
            // 无图片api
            url = "https://api.weibo.com/2/statuses/update.json"
            
            DBNetworkTool.shareNetworkTool.AFNManager.POST(url, parameters: parameters, progress: nil, success: { (_, response) -> Void in
                
                print("发布微博成功: \(response)")
                
                finish(error: nil)
                
                }) { (_, error) -> Void in
                    
                    finish(error: error)
            }
            
        } else {
            
            // 有图片api
            url = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            DBNetworkTool.shareNetworkTool.AFNManager.POST(url, parameters: parameters, constructingBodyWithBlock: { (fromData) -> Void in
                
                let imageData = UIImagePNGRepresentation(image!)
                
                fromData.appendPartWithFileData(imageData!, name: "pic", fileName: "hehe", mimeType: "image/png")
                
                }, progress: nil, success: { (_, success) -> Void in
                    
                    finish(error: nil)
                    
                }, failure: { (_, error) -> Void in
                    
                    print("上传图片失败:\(error)")
                    
                    finish(error: error)
            })
        }
    }
}














